package com.test.p10proxy.example01;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;

/**
 * @author bcc
 */
public class LoggerInvocationHandler implements InvocationHandler {

    private Object target;

    public LoggerInvocationHandler(Object target){
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("开始日志记录:" + new Date() + " " + (String) args[0] + " 查询数据");
        Object result = method.invoke(target, args);
        System.out.println("日志记录: 查询成功，结果为： " + result);
        System.out.println("Logger返回...");
        return result;
    }

    /**
     * 返回经过 LoggerInvocationHandler 包装的代理对象
     * @param target
     * @return
     */
    public static Object createProxy(Object target) {
        Class<?> allClass = target.getClass();
        return Proxy.newProxyInstance(allClass.getClassLoader(),allClass.getInterfaces(),new LoggerInvocationHandler(target));
    }
}
